package ar.com.jendrix.login.mail;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import ar.com.jendrix.common.exception.ApplicationException;
import ar.com.jendrix.common.exception.SystemException;
import ar.com.jendrix.common.util.IOUtil;

public class MailSender {

	public static final void send(MailMessage mailMessage) throws ApplicationException, SystemException {

		try {
			Properties config = getConfig();

			final Properties mailConfig = new Properties();
			mailConfig.put("mail.smtp.auth", config.getProperty("mail.smtp.auth"));
			mailConfig.put("mail.smtp.starttls.enable", config.getProperty("mail.smtp.starttls.enable"));
			mailConfig.put("mail.smtp.host", config.getProperty("mail.smtp.host"));
			mailConfig.put("mail.smtp.port", config.getProperty("mail.smtp.port"));

			final String username = config.getProperty("mail.from.username");
			final String password = config.getProperty("mail.from.password");

			Session session = Session.getInstance(mailConfig, new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			});

			// Construimos el Mensaje
			Message message = new MimeMessage(session);
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailMessage.getTo(), "lalala"));
			message.setSubject(mailMessage.getSubject());
			message.setText(mailMessage.getMessage());

			// Enviamos el Mensaje
			Transport.send(message);

		} catch (ApplicationException aex) {
			throw aex;
		} catch (AuthenticationFailedException afex){
			throw new ApplicationException("Error configurando la cuenta de mail origen!");
		} catch (MessagingException mex) {
			mex.printStackTrace();
			throw new ApplicationException("No se pudo leer el archivo de configuracion para enviar mails!");
		} catch (Throwable t) {
			t.printStackTrace();
			throw new SystemException(t);
		}
	}

	private static Properties getConfig() throws ApplicationException {
		Properties config = new Properties();
		InputStream configFile = null;
		try {
			// cargamos el archivo de propiedades
			configFile = Thread.currentThread().getContextClassLoader()
	                 .getResourceAsStream("mail.properties");			
			
			//configFile = new FileInputStream("mail.properties");
			config.load(configFile);
		} catch (IOException e) {
			throw new ApplicationException("Archivo mail.properties no definido");
		} finally {
			IOUtil.closeFile(configFile);
		}
		return config;
	}
}
